package com.manning.s2ip.actions;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.manning.s2ip.dao.PersonDao;
import com.manning.s2ip.entities.Person;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@Results({
	@Result(name="list", type="json", params={"root","personList"} ),
	@Result(name="input", type="json", params={"root","fieldErrors"} )
	})
public class PersonAction extends ActionSupport implements Preparable {
	
	private Person person;
	private List<Person> personList;
	private PersonDao personDao;
	
	public void prepare() {
		person = new Person();
	}
	
	@Override
	@SkipValidation
	public String execute() {
    	
        return SUCCESS;
        
    }
	
	@Action("person-submit")
	public String update() {
		if ( person.getKey() != null ) {
			personDao.update(person);
		}
		else {
			personDao.create(person);
		}
		personList = personDao.findAll();
		return "list";
	}
	
	@SkipValidation
	@Action("person-delete")
	public String delete() {
		person = personDao.read(person);
		personDao.delete(person);
		personList = personDao.findAll();
		return "list";
	}
    
	@SkipValidation
	@Action("person-list")
    public String list() {
		personList = personDao.findAll();
    	return "list";
    }

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	public List<Person> getPersonList() {
		return personList;
	}

}
